package cn.huijielong.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.huijielong.common.exception.VSException;
import sun.misc.BASE64Decoder;

public class Base64Upload {
	private static Logger logger = LoggerFactory.getLogger(VSUtil.class);

	public static void uploadMutilImage(String base64, File imgPath) {

		try {

			byte[] data = decode(base64);
			org.apache.commons.io.FileUtils.writeByteArrayToFile(imgPath, data);
		} catch (Exception ex) {
			logger.error("图片保存出错：{}" ,imgPath.getPath(), ex);
			throw new VSException(ex);
		}
	}

	private static byte[] decode(String imageData) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] data = decoder.decodeBuffer(imageData);
		for (int i = 0; i < data.length; ++i) {
			if (data[i] < 0) {
				// 调整异常数据
				data[i] += 256;
			}
		}
		//
		return data;
	}
}
